package cn.tedu.wx.controller;

import cn.tedu.wx.util.HttpClientUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
public class UserInfoController {
    //callBack修改成自己的
    String callBack = "http://w20216.webproxy.net.cn/";
    //appId修改成自己的
    String appId="wx8dcacec07e64877f";
    //secret修改成自己的
    String secret="8985e1b003531f0f470d3772a76e21aa";

    @RequestMapping("/userInfo/login")
    public void wxLogin(HttpServletResponse response) throws IOException {
        //请求获取code的回调地址
        //用线上环境的域名或者用内网穿透，不能用ip

        System.out.println("进入登陆状态了......");
        //请求地址
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize" +
                "?appid=" + appId +
                "&redirect_uri=" + URLEncoder.encode(callBack) +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=STATE#wechat_redirect";
        //System.out.println(url);
        //重定向
       response.sendRedirect(url);

        //HttpClientUtil.doGet(url);
    }

    //	回调方法
    @RequestMapping("/callBack")
    public String wxCallBack(HttpServletRequest request) throws IOException {
        System.out.println("回掉方法.....");
        String code = request.getParameter("code");
        System.out.println(code);
        //获取access_token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" + appId +
                "&secret=" + secret +
                "&code=" + code +
                "&grant_type=authorization_code";

        String result = HttpClientUtil.doGet(url);
        System.out.println("请求获取access_token:" + result);
        //返回结果的json对象
        JSONObject resultObject = JSON.parseObject(result);

        //请求获取userInfo
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=" + resultObject.getString("access_token") +
                "&openid=" + resultObject.getString("openid") +
                "&lang=zh_CN";
        String resultInfo = HttpClientUtil.doGet(infoUrl);
        System.out.println("取到用户信息如下：");
        System.out.println(resultInfo);
        return  resultInfo;

    }
}